export const getStoredToken = (): string | null => {
  try {
    let tokenFromUserData: string | null = null;
    try {
      const raw = localStorage.getItem('userData');
      if (raw) {
        const parsed = JSON.parse(raw);
        const candidate = parsed?.user_token;
        if (candidate && typeof candidate === 'string') {
          const trimmed = candidate.trim();
          if (trimmed) tokenFromUserData = trimmed;
        }
      }
    } catch {
      tokenFromUserData = null;
    }

    if (tokenFromUserData) return tokenFromUserData;

    const legacy = localStorage.getItem('token');
    if (legacy && typeof legacy === 'string') {
      const trimmed = legacy.trim();
      if (trimmed) return trimmed;
    }
  } catch {
    // ignore
  }
  return null;
};

export const getStoredBearerToken = (): string | null => {
  const token = getStoredToken();
  if (!token) return null;
  const lower = token.toLowerCase();
  return lower.startsWith('bearer ') ? token : `Bearer ${token}`;
};

export const hasStoredToken = (): boolean => !!getStoredToken();

